<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('multilingual.prodInspection')" @clickRight="clickRight"
				scanType="1" rightType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="distributed">
				<view class="card-mini">
					<view class="gui-form-item gui-border-b">
						<text class="gui-form-label gui-secondary-text">{{ $t('translationImage.process') }}</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							<superweiCombox style="text-align: right;" :candidates="data.processList"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true" keyName="text"
								@select="selectProcess" v-model="data.processText"></superweiCombox>
						</view>
					</view>
					<view class="gui-form-item gui-border-b">
						<text class="gui-form-label gui-secondary-text">{{ $t('multilingual.productionLine') }}</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">

							<superweiCombox style="text-align: right;" :candidates="data.productLineList"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true"
								keyName="productionLineCode" @select="selectProductLine" v-model="data.productLineId"
								:emptyTips="$t('pageTranslation.pleaseSelectThe')"></superweiCombox>
						</view>
					</view>

					<view class="gui-form-item">
						<text
							class="gui-form-label gui-secondary-text">{{ $t('multilingual.amountDefectiveGoods') }}：</text>
						<view class="gui-form-body gui-text-right" style="overflow: visible;">
							{{ totalNum }}
						</view>
					</view>
				</view>
				<view class="card-mini" v-if="data.productLineId">
					<view class="card-mini-body">
						<view class="card-mini-item addmargin">
							<view class="mini-item-50">
								<text
									class="mini-item-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ data.productLineInfo.outputMaterialCode }}
							</view>
							<view class="mini-item-50">
								<text
									class="mini-item-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.productLineInfo.outputMaterialName }}
							</view>
						</view>
						<view class="card-mini-item">
							<view style="width:100%" class="mini-item-50">
								<text
									class="mini-item-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.productLineInfo.productionMaterialSpec }}
							</view>
						</view>
					</view>
				</view>
				<!-- 底部显示区域 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view class="card-mini nomargintop" v-if="data.processId">
						<view class="card-mini-body">
							<view v-for="(item, index) in data.defectiveItems"
								:key="`${item.productionCheckName}` + `${index}`"
								class="card-mini-item flexcenter gui-space-between" style="font-size: 32rpx;">
								<text>{{ item.productionCheckName }}：</text>
								<uni-number-box v-model="item.number" @change="changeValue"  />
							</view>
						</view>
						<view style="height:20rpx"></view>
					</view>
				</scroll-view>
				<view class="page-bottom-box" @click="scanConfirmFn" v-if="data.processText!='TH'&&data.processText!='JKJ'&&data.processText!='DR'">
					<view class="page-bottomBtn bottomBtn-bgcolor-green">{{$t('calendar.submit')}}</view>
				</view>
				<view class="page-bottom-box" @click="submit" v-else>
					<view class="page-bottomBtn bottomBtn-bgcolor-green">{{$t('calendar.submit')}}</view>
				</view>
			</view>
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view class="input-dialog-content" style="height: 300rpx;">
						<view class="gui-form-item gui-border-b">
							<text style="width: 200rpx;">{{ $t('mexico.defectiveLocation') }}：</text>
							<superweiCombox style="text-align: left;" :candidates="data.positionOption"
								:placeholder="$t('pageTranslation.plsChooseDrop')" :isJSON="true" keyName="text"
								@select="change" v-model="data.position2" ></superweiCombox>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="submit">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>
<script setup>
import searchCustom from '@/components/searchCustom';
import superweiCombox from '@/components/superweiCombox';
import calendarCustom from '@/components/calendarCustom';
import {ref,reactive,onMounted,getCurrentInstance,computed,watch,watchEffect} from 'vue';
import {findLineByProcessCode,findCheckDataProductTest,commitErrorRecord} from '@/api/api.js'
import {getDataDictionaryFn,pitchOnFn} from '@/utils/index.js'
import { onShow } from '@dcloudio/uni-app';
import graceJS from "@/Grace6/js/grace.js";
import { navigate } from '@/utils/routerSkip.js';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT } from '@/constant/index.js'
import uniNumberBox from '@/components/uni-number-box/uni-number-box';

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

components: {
	superweiCombox,
		searchCustom,
		calendarCustom
}
let calendarCustomRef = ref(null);
let inputDialog=ref(null)
const {ctx} = getCurrentInstance();

let data = reactive({
	processList: [], //工序数据
	processId: '', //用户选中工序
	processText: '', //用户选中工序
	productLineList: [],
	productLineId: '',
	productLineText: '',
	productLineInfo: {},
	defectiveItems: [],
	position: 1,
	position2: '',
	positionOption: [
		// { value: 1, text: t('mexico.JKJOutInput') },
		{ value: 2, text: t('mexico.JKJOutInputLight') },
		{ value: 3, text: t('mexico.PEFilm') },
		// { value: 4, text: t('mexico.PEOutInput') },
	]
});
let totalNum = computed(() => {
	let num = 0;
	data.defectiveItems.forEach(x => {
		num += x.number
	})
	return num
})




//监听
watch(() => data.defectiveItems, (newVal, oldVal) => {
	console.log(newVal)
	
}, {
	immediate: true,
	deep: true
});


onMounted(() => {
	getInitData()
})
onShow(() => {

})

// 用户选中工序 
const selectProcess = (etv) => {
	data.processId = etv.value;
	data.processText = etv.text;
	data.productLineList = [];
	data.productLineId = '';
	data.productLineText = '';
	if (data.processText == "TH") {
		data.position = 1
	}

	if (data.processText == "JKJ") {
		data.position = 1
	}

	if (data.processText == "DR") {
		data.position = 4
		data.processId="PE"
	}
	console.log(data)
	findLineByProcessCodeFn();
	findCheckDataProductTestFn();
}
// 获取工序数据
const getInitData = async () => {
	// 获取调入组织信息
	await getDataDictionaryFn('ProductionProcesses').then(res=>{
		if(res.code==0){
			data.processList = res.data
		}
	})
	let tepSelect1 = pitchOnFn(data.processList)
	if (tepSelect1.length) {
		data.processId = tepSelect1[0].value
		data.processText = tepSelect1[0].text
	}
}

// 根据工序查询次品项
const findCheckDataProductTestFn = () => {
	findCheckDataProductTest({
		checkProcessCode: data.processId
	}).then(res => {
		if (res.code == 0) {
			data.defectiveItems = res.data;
			data.defectiveItems.forEach(x => {
				x.number = 0
			})
		} else {
			uni.showToast({ title: res.message, icon: 'none' })
		}
	})
}
// 用户选择产线
const selectProductLine = (etv) => {
	console.log('用户选择产线后',etv)
	data.productLineId = etv.productionLineCode;
	data.productLineText = etv.productionLineName;
	data.productLineInfo = etv;
}
// 根据用户选中的工序查询产线
const findLineByProcessCodeFn = () => {
	findLineByProcessCode({
		checkProcessCode: data.processId
	}).then(res => {
		if (res.code == 0) {
			data.productLineList = res.data
		} else {
			uni.showToast({ title: res.message, icon: 'none' })
		}
	})
}

	// 点位选择
	const change=(e)=>{
		data.position = e.value
		if(data.position==2){  //JKJ
			findLineByProcessCode({
				checkProcessCode:'JKJ'
			}).then(res=>{
				if (res.code == 0) {
					var lineList = res.data
					var lineInfo=lineList.filter(e=>e.productionLineCode==data.productLineId)[0]
					console.log(lineInfo)
					data.productLineId = lineInfo.productionLineCode;
					data.productLineText = lineInfo.productionLineName;
					data.productLineInfo = lineInfo;
					data.processId='JKJ'
					data.processCode='JKJ'
					data.processName='JKJ'
					data.processText='JKJ'
					
				}else{
					uni.showToast({title: res.msg,icon: 'none'})
				}
			})
		}
	}
	// 提交弹框
	const scanConfirmFn=()=>{
		inputDialog.value.open()
		
	}
	const cancelFn=()=>{
		data.position2=''
		inputDialog.value.close()
	}

// 提交
const submit = () => {
	//console.log('submit');
	console.log(data.defectiveItems, 'data.defectiveItems');
	if (!data.processId) {
		uni.showToast({ title: t('JsInternational.chooseOperation'), icon: 'none' })
		return
	}
	if (!data.productLineId) {
		uni.showToast({ title: t('JsInternational.chooseLine'), icon: 'none' })
		return
	}
	if (!data.productLineInfo.outputMaterialCode) {
		uni.showToast({ title: t('JsInternational.productionLine'), icon: 'none' })
		return
	}
	console.log(totalNum.value, 'totalNumtotalNumtotalNum');
	if (totalNum.value == 0) {
		uni.showToast({ title: t('JsInternational.chooseDefective'), icon: 'none' })
		return
	}
	if (data.position2 == '' && data.processText != 'TH' && data.processText != 'JKJ' && data.processText != 'DR') {
		uni.showToast({ title: t('locationBarcodeInfo.pleaseLocations'), icon: 'none' })
		return
	}
	
	let tepArry = [];
	tepArry = data.defectiveItems.map(x => {
		return {
			productionCheckCode: x.productionCheckCode,
			productionCheckName: x.productionCheckName,
			errorQty: x.number,
		}
	})
	let parmes = {
		processCode: data.processId,
		processName: data.processText=="DR"?"PE":data.processText,
		productionLineCode: data.productLineId,
		productionLineName: data.productLineText,
		materialCode: data.productLineInfo.outputMaterialCode,
		materialName: data.productLineInfo.outputMaterialName,
		qmsProductionCheckList: tepArry,
		position:data.position
	}

	uni.showLoading({
		title: t('mexico.systemIsWait'),
		mask: true
	})

	commitErrorRecord(parmes).then(res => {
		uni.hideLoading()
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '生产检验'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module:'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: 'none' })
			data.processId = ''
			data.processText = ''
			data.productLineId = ''
			data.productLineText = ''
			data.productLineList = []
			data.productLineInfo = {}
			data.defectiveItems = []
			inputDialog.value.close()
			data.position2=''
		} else {
			uni.showToast({ title: res.msg, icon: 'none' })
		}
	}).catch(error=>{
		uni.hideLoading()
		uni.showToast({ title: error.data.msg, icon: 'none' })
	})
}

const select = (e) => {
	console.log(e);
}
const clickRight = () => {
	navigate({
		url: '/pages/market/checkoutHistory'
	})
}
const goPage = (x) => {
	navigate({
		url: `/pages/market/stockRemovalDetail?id=${x.id}`
	})
}
const changeValue = (e) => {
	console.log(e)
}
</script>
<style lang="scss" scoped>
.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	margin-top: 20rpx;
	height: 2rpx;
}

.nomargintop {
	margin-top: 0px !important;
}

.card-mini-body {
	height: auto !important;
}

.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.card-box {
	margin: 0 15rpx;
	box-shadow: 0rpx 0rpx 4rpx 0 #A5A5A5;
	background: #fff;
	padding: 30rpx;
	border-radius: 16rpx;
}

.card-item {
	line-height: 60rpx;
}

.card-bottom {
	margin-bottom: 30rpx;
}

.filtrate-item {
	display: flex;
	align-items: center;
	font-size: 32rpx;
	margin-bottom: 20rpx;

	.filtrate-itemLeft {
		height: 32rpx;
		line-height: 32rpx;
		width: 100rpx;
	}

	.filtrate-itemRight {
		border: 2rpx solid #A5A5A5;
		border-radius: 8rpx;
		overflow: hidden;
		line-height: 40rpx;
		width: 300rpx;
	}
}

// 展开按钮样式
.card-rotating-top {
	margin-top: 30rpx;
}

.addmargin {
	margin-bottom: 30rpx;
}

.mini-item-title {
	font-size: 25rpx;
}

.flexcenter {
	align-items: center;
	height: 90rpx;

	::v-deep .uni-numbox-btns {
		padding: 0 28rpx;
	}

	::v-deep .uni-numbox__value {
		width: 100rpx;
	}
}

.card-selectCustom {
	margin: 0.46875rem 0.625rem;
	box-shadow: 0 0 0.125rem 0 #a5a5a5;
	background: #fff;
	padding: 0.375rem 0.75rem;
	border-radius: 0.5rem;
	position: relative;
	height: 70rpx;
}

.scrollview {
	margin-top: 20rpx;
	padding-bottom: 200rpx;
}

.gui-secondary-text {
	color: #4f4f4f;
}

.gui-form-label {
	width: auto !important;
}

.page-bottom-box {
	position: fixed;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>
